// 配置Phaser游戏实例
const config = {
    type: Phaser.AUTO,
    scale: {
        mode: Phaser.Scale.RESIZE,
        parent: 'game',
        width: '100%',
        height: '100%',
        min: {
            width: 320,
            height: 480
        },
        max: {
            width: 1920,
            height: 1080
        },
        autoCenter: Phaser.Scale.CENTER_BOTH
    },
    backgroundColor: '#F5E6CA',
    scene: {
        preload: preload,
        create: create,
        update: update
    }
};

// 游戏状态
const gameState = {
    score: 0,
    attempts: 0,
    maxAttempts: 10,
    currentLevel: 0,
    currentE: null,
    currentDirection: null,
    gameStarted: false,
    fontSize: 22,
    levels: [
        { size: 120, vision: 4.0 },
        { size: 96, vision: 4.1 },
        { size: 78, vision: 4.2 },
        { size: 64, vision: 4.3 },
        { size: 52, vision: 4.4 },
        { size: 42, vision: 4.5 },
        { size: 34, vision: 4.6 },
        { size: 27, vision: 4.7 },
        { size: 22, vision: 4.8 },
        { size: 18, vision: 4.9 },
        { size: 15, vision: 5.0 },
        { size: 12, vision: 5.1 },
        { size: 10, vision: 5.2 }
    ],
    gameStartTime: null
};

// 创建游戏实例
const game = new Phaser.Game(config);

// 防抖函数
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

// 预加载资源
function preload() {
    this.load.image('E_up', 'img/E_up.png');
    this.load.image('E_right', 'img/E_right.png');
    this.load.image('E_down', 'img/E_down.png');
    this.load.image('E_left', 'img/E_left.png');
}

// 创建游戏场景
function create() {
    this.cursors = this.input.keyboard.createCursorKeys();
    createScoreDisplay.call(this);
    showInstructions.call(this);
    
    // 添加窗口大小变化监听器
    const debouncedResize = debounce((gameSize) => {
        handleResize.call(this, gameSize);
    }, 100);
    
    // 监听Phaser的resize事件
    this.scale.on('resize', debouncedResize);
    
    // 监听窗口resize事件
    window.addEventListener('resize', () => {
        const gameSize = {
            width: this.scale.width,
            height: this.scale.height
        };
        debouncedResize(gameSize);
    });
}

// 更新游戏状态
function update() {
    if (!gameState.gameStarted || gameState.attempts >= gameState.maxAttempts) return;
    
    // 添加一个短暂的延迟，避免游戏开始时的按键被计入
    if (gameState.gameStartTime && Date.now() - gameState.gameStartTime < 100) return;
    
    if (Phaser.Input.Keyboard.JustDown(this.cursors.left)) {
        checkAnswer.call(this, 'left');
    } else if (Phaser.Input.Keyboard.JustDown(this.cursors.right)) {
        checkAnswer.call(this, 'right');
    } else if (Phaser.Input.Keyboard.JustDown(this.cursors.up)) {
        checkAnswer.call(this, 'up');
    } else if (Phaser.Input.Keyboard.JustDown(this.cursors.down)) {
        checkAnswer.call(this, 'down');
    }
}

// 创建分数显示
function createScoreDisplay() {
    const padding = 20;
    const cornerRadius = 12;
    
    // 创建容器
    const scoreContainer = this.add.container(padding, 80);
    
    // 创建背景
    const background = this.add.graphics();
    background.fillStyle(0xFFFFFF, 0.95);
    background.lineStyle(2, 0x4CAF50);
    
    // 创建文本
    const scoreText = this.add.text(padding, padding, '正确次数: 0', {
        fontSize: `${gameState.fontSize}px`,
        fill: '#333333',
        fontFamily: '"Noto Sans SC", sans-serif',
        fontWeight: 'bold'
    });
    
    const attemptsText = this.add.text(padding, padding + 35, `尝试次数: 0 / ${gameState.maxAttempts}`, {
        fontSize: `${gameState.fontSize}px`,
        fill: '#333333',
        fontFamily: '"Noto Sans SC", sans-serif',
        fontWeight: 'bold'
    });
    
    // 计算背景大小
    const width = Math.max(scoreText.width, attemptsText.width) + (padding * 2);
    const height = scoreText.height + attemptsText.height + (padding * 2);
    
    // 绘制背景
    background.fillRoundedRect(0, 0, width, height, cornerRadius);
    background.strokeRoundedRect(0, 0, width, height, cornerRadius);
    
    // 添加到容器
    scoreContainer.add([background, scoreText, attemptsText]);
    
    // 保存引用
    this.scoreDisplay = {
        container: scoreContainer,
        background: background,
        scoreText: scoreText,
        attemptsText: attemptsText
    };
}

// 更新分数显示
function updateScoreDisplay() {
    const { scoreText, attemptsText } = this.scoreDisplay;
    scoreText.setText(`正确次数: ${gameState.score}`);
    attemptsText.setText(`尝试次数: ${gameState.attempts} / ${gameState.maxAttempts}`);
    
    // 更新背景大小
    const padding = 20;
    const width = Math.max(scoreText.width, attemptsText.width) + (padding * 2);
    const height = scoreText.height + attemptsText.height + (padding * 2);
    
    this.scoreDisplay.background.clear();
    this.scoreDisplay.background.fillStyle(0xFFFFFF, 0.95);
    this.scoreDisplay.background.lineStyle(2, 0x4CAF50);
    this.scoreDisplay.background.fillRoundedRect(0, 0, width, height, 12);
    this.scoreDisplay.background.strokeRoundedRect(0, 0, width, height, 12);
}

// 显示下一个E字
function showNextE() {
    if (gameState.currentE) {
        gameState.currentE.container.destroy();
        gameState.currentE = null;
    }
    
    if (gameState.attempts >= gameState.maxAttempts) {
        showResult.call(this);
        return;
    }
    
    const level = gameState.levels[gameState.currentLevel];
    const directions = ['up', 'right', 'down', 'left'];
    gameState.currentDirection = Phaser.Math.RND.pick(directions);
    
    // 获取当前游戏区域尺寸
    const width = this.scale.width;
    const height = this.scale.height;
    
    // 计算容器尺寸
    const rectWidth = Math.min(width * 0.5, 500);
    const rectHeight = Math.min(height * 0.3, 350);
    
    // 创建容器并设置到中心位置
    const container = this.add.container(width / 2, height / 2);
    
    // 创建背景
    const background = this.add.rectangle(0, 0, rectWidth, rectHeight, 0xFFFFFF);
    background.setStrokeStyle(1, 0x000000);
    
    // 创建E字并确保居中
    const eImage = this.add.image(0, 0, `E_${gameState.currentDirection}`);
    const scale = level.size / eImage.width;
    eImage.setScale(scale);
    
    // 将元素添加到容器
    container.add([background, eImage]);
    
    // 保存状态和引用
    gameState.currentE = { 
        container, 
        background, 
        image: eImage,
        width: rectWidth,
        height: rectHeight,
        scale: scale
    };
    
    // 确保容器位于视图中心
    centerContainer(this, container, rectWidth, rectHeight);
}

// 检查答案
function checkAnswer(userDirection) {
    gameState.attempts++;
    
    if (userDirection === gameState.currentDirection) {
        gameState.score++;
        if (gameState.currentLevel < gameState.levels.length - 1) {
            gameState.currentLevel++;
        }
    } else if (gameState.currentLevel > 0) {
        gameState.currentLevel--;
    }
    
    updateScoreDisplay.call(this);
    showNextE.call(this);
}

// 显示结果
function showResult() {
    if (gameState.currentE) {
        gameState.currentE.container.destroy();
        gameState.currentE = null;
    }
    
    const vision = gameState.levels[gameState.currentLevel].vision;
    const accuracy = (gameState.score / gameState.maxAttempts) * 100;
    
    // 生成结果文本
    const resultText = `您的视力大约为: ${vision.toFixed(1)}\n准确率: ${accuracy.toFixed(1)}%`;
    
    // 根据视力值生成建议
    let advice = '';
    if (vision >= 5.0) {
        advice = '您的视力状况良好！建议：\n• 继续保持良好的用眼习惯\n• 适当的户外活动和运动\n• 每年进行一次视力检查';
    } else if (vision >= 4.5) {
        advice = '您的视力轻微下降。建议：\n• 增加户外活动时间\n• 保持正确的读写姿势\n• 每隔半年进行一次视力检查\n• 控制电子产品使用时间';
    } else {
        advice = '您的视力需要关注。建议：\n• 及时就医进行专业检查\n• 调整作息时间，确保充足睡眠\n• 保持正确的用眼习惯\n• 可能需要配戴眼镜或调整镜片度数';
    }
    
    const modal = document.getElementById('resultModal');
    const resultDisplay = document.getElementById('resultText');
    const adviceDisplay = document.getElementById('adviceText');
    const restartBtn = document.getElementById('restartButton');
    
    resultDisplay.innerHTML = resultText.replace(/\n/g, '<br>');
    adviceDisplay.innerHTML = advice.replace(/\n/g, '<br>');
    modal.style.display = 'block';
    
    restartBtn.onclick = () => {
        modal.style.display = 'none';
        resetGame.call(this);
    };
    
    window.onclick = (event) => {
        if (event.target === modal) {
            modal.style.display = 'none';
        }
    };
}

// 重置游戏
function resetGame() {
    Object.assign(gameState, {
        score: 0,
        attempts: 0,
        currentLevel: 0,
        currentE: null,
        currentDirection: null
    });
    
    updateScoreDisplay.call(this);
    showNextE.call(this);
}

// 显示说明
function showInstructions() {
    const modal = document.getElementById('instructionModal');
    const startButton = document.getElementById('startButton');
    modal.style.display = 'block';
    
    const handleStart = () => {
        if (!gameState.gameStarted) {
            gameState.gameStarted = true;
            gameState.gameStartTime = Date.now();
            modal.style.display = 'none';
            window.removeEventListener('keydown', handleStart);
            startGame.call(this);
        }
    };
    
    window.addEventListener('keydown', handleStart);
    startButton.onclick = handleStart;
}

// 开始游戏
function startGame() {
    resetGame.call(this);
}

// 处理窗口大小变化
function handleResize(gameSize) {
    const width = gameSize.width;
    const height = gameSize.height;
    
    // 更新字体大小
    gameState.fontSize = calculateFontSize(width);
    
    // 更新分数显示
    if (this.scoreDisplay) {
        this.scoreDisplay.scoreText.setFontSize(gameState.fontSize);
        this.scoreDisplay.attemptsText.setFontSize(gameState.fontSize);
        updateScoreDisplay.call(this);
        
        // 更新计分板位置
        const padding = width < 768 ? 10 : 20;
        this.scoreDisplay.container.setPosition(padding, 80);
    }
    
    // 更新E字位置和大小
    if (gameState.currentE) {
        // 计算新的背景尺寸
        const rectWidth = Math.min(width * 0.5, 500);
        const rectHeight = Math.min(height * 0.3, 350);
        
        // 更新背景尺寸
        const background = gameState.currentE.background;
        background.setSize(rectWidth, rectHeight);
        
        // 更新E字位置和缩放
        const eImage = gameState.currentE.image;
        const level = gameState.levels[gameState.currentLevel];
        const scale = level.size / eImage.width;
        eImage.setScale(scale);
        eImage.setPosition(0, 0);
        
        // 保存新的尺寸
        gameState.currentE.width = rectWidth;
        gameState.currentE.height = rectHeight;
        gameState.currentE.scale = scale;
        
        // 重新居中容器
        centerContainer(this, gameState.currentE.container, rectWidth, rectHeight);
    }
    
    // 强制更新场景
    this.scene.resume();
}

// 居中容器的辅助函数
function centerContainer(scene, container, width, height) {
    // 获取游戏区域尺寸
    const gameWidth = scene.scale.width;
    const gameHeight = scene.scale.height;
    
    // 计算中心位置
    const centerX = gameWidth / 2;
    const centerY = gameHeight / 2;
    
    // 设置容器位置
    container.setPosition(centerX, centerY);
    
    // 确保容器在视图范围内
    const bounds = {
        left: centerX - width / 2,
        right: centerX + width / 2,
        top: centerY - height / 2,
        bottom: centerY + height / 2
    };
    
    // 调整位置以确保完全可见
    if (bounds.left < 0) {
        container.x += Math.abs(bounds.left);
    } else if (bounds.right > gameWidth) {
        container.x -= (bounds.right - gameWidth);
    }
    
    if (bounds.top < 0) {
        container.y += Math.abs(bounds.top);
    } else if (bounds.bottom > gameHeight) {
        container.y -= (bounds.bottom - gameHeight);
    }
}

// 计算字体大小
function calculateFontSize(width) {
    if (width < 768) return 20;
    if (width < 1024) return 22;
    return 24;
}